#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
录制片段模型
"""

from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Float, BigInteger
import json
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.core.database import Base

class Segment(Base):
    __tablename__ = "segments"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(200), nullable=False, comment="片段名称")
    
    # 关联信息
    recording_id = Column(Integer, ForeignKey("recordings.id"), nullable=False, comment="关联录制ID")
    task_id = Column(Integer, ForeignKey("tasks.id"), nullable=False, comment="关联任务ID")
    
    # 片段信息
    start_time = Column(Float, nullable=False, comment="开始时间(秒)")
    end_time = Column(Float, nullable=False, comment="结束时间(秒)")
    duration = Column(Float, nullable=False, comment="时长(秒)")
    
    # 文件信息
    file_path = Column(String(500), nullable=False, comment="文件路径")
    file_size = Column(BigInteger, default=0, comment="文件大小(字节)")
    
    # 内容分析
    content_type = Column(String(50), nullable=True, comment="内容类型")
    quality_score = Column(Float, default=0.0, comment="质量评分")
    
    # 关键帧信息
    keyframe_path = Column(String(500), nullable=True, comment="关键帧路径")
    thumbnail_path = Column(String(500), nullable=True, comment="缩略图路径")
    
    # 元数据
    extra_metadata = Column(Text, default="{}", comment="额外元数据 JSON格式")
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    recording = relationship("Recording", backref="segments")
    task = relationship("Task", backref="segments")
    
    def __repr__(self):
        return f"<Segment(id={self.id}, name={self.name}, duration={self.duration})>"
    
    def to_dict(self):
        try:
            metadata_dict = json.loads(self.extra_metadata) if self.extra_metadata else {}
        except (json.JSONDecodeError, TypeError):
            metadata_dict = {}
        
        return {
            "id": self.id,
            "name": self.name,
            "recording_id": self.recording_id,
            "task_id": self.task_id,
            "start_time": self.start_time,
            "end_time": self.end_time,
            "duration": self.duration,
            "file_path": self.file_path,
            "file_size": self.file_size,
            "content_type": self.content_type,
            "quality_score": self.quality_score,
            "keyframe_path": self.keyframe_path,
            "thumbnail_path": self.thumbnail_path,
            "extra_metadata": metadata_dict,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }